<template>
  <div class="hotWord">
    <!-- 功能按钮 -->
    <div class="hotWord_button">
      <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <div class="hot-sec">热词分组：<span>{{ query.cateName }}</span></div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.hotWordGroupColumns" :dataSource="configData.records" ref="hotDetailBaseTables"
      :isSelect="true" :scroll="scroll" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage" @deleteRecord="deleteSelectedAll">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <template v-if="column.dataIndex === 'linkUrl'">
            <a><table-tool-tip :text="text" :column="column"></table-tool-tip></a>
          </template>
          <template v-else>
            <table-tool-tip :text="text" :column="column"></table-tool-tip>
          </template>
        </template>
        <template v-if="column.dataIndex === 'isTargetBlank'">
          {{ record.isTargetBlank ? "是" : "否" }}
        </template>
        <template v-if="column.dataIndex === 'isEnable'">
          <a-switch size="small" v-model:checked="record.isEnable" @click="switchChange(record)" />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('moveAble') }" @click="moveHotWord(record)">{{
            record.oparation[0]
          }}</a>
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">{{
            record.oparation[1] }}</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                删除此热词后，引用到此热词的文章，内容中所有的热词链接将无效，变成正常的正文词语
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[2] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="moveAll"
          :disabled="!rowSelection.length || !btnPerm.includes('moveAble')">移动</a-button>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('moveAble')">删除</a-button>
      </template>
    </baseTable>

    <!-- 新建热词模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="hotword_detail_modal">
      <template v-slot:body>
        <a-form name="advanced_search" :class="modAlProps.title === '移动热词' ? 'hotwordform' : 'editDetailHotWordForm'"
          autoComplete="off" :model="formState" ref="hotDetailFrom" v-if="isVisible">
          <template v-if="isAddOrEdit">
            <a-form-item :name="['hotWordGroup', 'value']" :label="formState.hotWordGroup.label"
              :rules="[formState.hotWordGroup.rule]">
              <span>{{ cateName }}</span>
            </a-form-item>
            <a-form-item :name="['hotWordVocabulary', 'value']" :label="formState.hotWordVocabulary.label"
              :rules="[formState.hotWordVocabulary.rule]">
              <a-input v-model:value="formState.hotWordVocabulary.value" placeholder="不超过25个字" show-count :maxlength="25"
                allow-clear />
            </a-form-item>
            <a-form-item :name="['linkUrl', 'value']" :label="formState.linkUrl.label" :rules="[formState.linkUrl.rule]">
              <a-input v-model:value="formState.linkUrl.value" placeholder="热词点击跳转的链接" allow-clear />
            </a-form-item>
            <a-form-item :label="formState.remark.label" :rules="[formState.remark.rule]">
              <a-textarea style="position: relative; height: 80px" v-model:value="formState.remark.value"
                placeholder="不超过200个字" show-count :maxlength="200" />
            </a-form-item>
            <a-form-item :label="formState.isEnable.label" :rules="[formState.isEnable.rule]">
              <a-switch size="small" v-model:checked="formState.isEnable.value" />
            </a-form-item>
            <a-form-item label="新窗口打开:" :rules="[{ required: true }]">
              <a-radio-group v-model:value="formState_redio_new">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item v-if="addCopySelect" label="重复热词:" :rules="[{ required: true }]">
              <a-radio-group v-model:value="formState_redio">
                <a-radio value="1">覆盖重复项</a-radio>
                <a-radio value="2">跳过重复项</a-radio>
              </a-radio-group>
              <p class="model-tip">若热词覆盖，则以前的使用次数以及点击次数将重计</p>
            </a-form-item>
          </template>
          <template v-else>
            <p class="move-title">{{ moveNameValue }}</p>
            <a-form-item class="move-item" :name="['moveHotWord', 'value']" :label="formState.moveHotWord.label"
              :rules="[formState.moveHotWord.rule]">
              <a-select placeholder="请选择" v-model:value="formState.moveHotWord.value" @change="changeHotword"
                :options="moveOptions"></a-select>
              <div style="font-size: 12px; margin-top: 8px; color: #00000073">
                移动后点击次数以及引用次数将重置
              </div>
            </a-form-item>
          </template>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import { useRoute } from "vue-router";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import type { SelectProps } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { checkHotWord } from "./formRuler";
import { routerPerm } from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};

type moveObject = {
  categoryId: number;
  ids: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  hotWord: dataSourceType;
  password: string;
  remember: boolean;
}

//data
const btnPerm = ref<any[]>([]);
let scroll: scrollType = reactive({ y: "", isFixed: false
, x: '200%'}); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let moveParams: moveObject = reactive({
  categoryId: 0,
  ids: [],
});

//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let rowSelection = ref<(string | number)[]>([]);
const hotDetailBaseTables = ref<any>(null);
const deleteArr = ref<(string | number)[]>([]);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const addCopySelect = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建热词分组",
});
let formState_redio = ref<string | number>("");
let formState_redio_new = ref<boolean>(true);
const hotDetailFrom = ref<any>("hotDetailFrom");
const { query } = useRoute();
const cateName = query.cateName;
//检测重复热词
const checkUnique = async (ref: any, value: any) => {
  if (value === "" || value.length === 0) {
    return Promise.reject(ref.message);
  }
  const params = {
    hotTerm: formState.hotWordVocabulary.value,
    id: ref.params.id,
  };

  let res = await request[`${ref.api}`](params);
  if (!res) {
    addCopySelect.value = true;
  } else {
    addCopySelect.value = false;
  }
  Promise.resolve();
};
const formState = reactive<dataSourceType>({
  hotWordGroup: {
    value: cateName,
    rule: {
      // validator: checkUnique,
      required: false,
      trigger: ["change", "blur"],
      message: "热词分组不可为空！",
    },
    label: "热词分组",
  },
  hotWordVocabulary: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "热词不可为空！",
      validator: checkUnique,
      api: "fetchHotwordUnique",
      params: { id: "" },
    },
    label: "热词词汇",
  },
  linkUrl: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "链接地址不可为空！",
    },
    label: "链接地址",
  },
  remark: {
    value: "",
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "热词备注不可为空！",
    },
    label: "热词备注",
  },
  isEnable: {
    value: true,
    rule: {
      required: false,
    },
    label: "是否启用",
  },
  moveHotWord: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "热词分组不可为空！",
    },
    label: "热词分组",
  },
  hotWordCategoryId: "",
  id: "",
  siteId: "",
});
let moveNameValue = ref<string | undefined>(undefined);
const moveOptions = ref<SelectProps["options"]>([]);

let datas = reactive({});

// 模板文件上传配置
const props_upload = reactive<dataSourceType>({
  action: "",
  accept: "xlsx,xls",
  directory: false,
  listType: "text",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//methods
const addRecord = (item: dataSourceType) => {
  //新加热词模态框条件修改
  //添加热词数据

  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建热词";
  formState.hotWordGroup.value = configData.records.length
    ? configData.records[0].cateName
    : "";
  formState.hotWordCategoryId = query.id;
  formState.hotWordVocabulary.value = "";
  formState.hotWordVocabulary.rule.params.id = "";
  addCopySelect.value = false;
  formState.linkUrl.value = "";
  formState.remark.value = "";
  formState.isEnable.value = true;
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  nextTick(() => {
    hotDetailFrom.value.resetFields();
  });
};

const eidtRecord = async (item: dataSourceType) => {
  if (!btnPerm.value.includes('editAble')) return
  //编辑热词数据
  const data = await request.fetchHotwordDetail({ id: item.id });
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "编辑热词";

  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  nextTick(() => {
    hotDetailFrom.value.resetFields();
    formState.hotWordGroup.value = data.cateName;
    formState.hotWordVocabulary.value = data.hotWord;
    formState.hotWordVocabulary.rule.params.id = data.id;
    formState.linkUrl.value = data.linkUrl;
    formState.remark.value = data.remark;
    formState.isEnable.value = data.isEnable;
    formState.hotWordCategoryId = data.hotWordCategoryId;
    formState.id = data.id;
  });
  // formState.hotWord.value = item.hotWord;
  // formState.replaceWord.value = item.replaceWord;
  // formState.id = item.key;
};

const changeHotword = (val: string, option: any) => {
  moveParams.categoryId = option.id;
};

const moveHotWord = (record: any) => {
  if (!btnPerm.value.includes('moveAble')) return
  //移动热词
  formState.moveHotWord.value;
  moveNameValue.value = `将热词：${record.hotWord} 移动到`;
  formState.moveHotWord.value = record.cateName;
  moveParams = {
    categoryId: formState.hotWordCategoryId,
    ids: [record.id],
  };

  fetchHotwordMove();
};

const fetchHotwordMove = () => {
  modAlProps.title = "移动热词";
  isVisible.value = true;
  isAddOrEdit.value = false;
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

// 新添或编辑热词调取接口
const buttonMessage = async (msg: dataSourceType) => {
  if (isAddOrEdit.value) {
    //保存
    hotDetailFrom.value
      .validate()
      .then(() => {
        let params: dataSourceType = {
          hotWord: formState.hotWordVocabulary.value,
          isTargetBlank: formState_redio_new.value,
          linkUrl: formState.linkUrl.value,
          remark: formState.remark.value,
          hotWordCategoryId: formState.hotWordCategoryId,
        };
        let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
        type === "Edit"
          ? (params = {
            id: formState.id,
            ...params,
          })
          : (params = {
            dealWithType: formState_redio.value,
            ...params,
          });

        request[type === "Edit" ? "fetchHotwordUpdate" : "fetchHotword"](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              message.success(res.message);
              formState.hotWordGroup.value = configData.records.length
                ? configData.records[0].cateName
                : "";
              formState.hotWordCategoryId = query.id;
              formState.hotWordVocabulary.value = "";
              formState.hotWordVocabulary.rule.params.id = "";
              addCopySelect.value = false;
              formState.linkUrl.value = "";
              formState.remark.value = "";
              getRecord(datas);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
        isVisible.value = msg.text == "保存" ? false : true;
      })
      .catch(() => { });
  } else {
    hotDetailFrom.value
      .validate()
      .then(() => {
        request
          .fetchHotwordMove(moveParams)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              message.success(res.message);
              getRecord(datas);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      })
      .catch(() => { });
    isVisible.value = msg.text == "保存" ? false : true;
    configData.records.length && hotDetailFrom.value.resetFields();
  }
};

// 删除单个热词
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};
//删除已选所有热词
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的热词？删除后无法恢复",
      content:
        "删除热词后，引用到热词的文章，内容中所有的热词链接将无效，变成正常的正文词语",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
//移动已选所有热词
const moveAll = async () => {
  let wordsList: string[] = [];
  let keys = rowSelection.value;
  configData.records.map((item) => {
    keys.find((key) => {
      if (item.id == key) {
        wordsList.push(item.hotWord);
      }
    });
  });
  moveNameValue.value =
    wordsList.length > 20
      ? `将热词：${wordsList.join("、")}...等${wordsList.length}个词汇移动到`
      : `将热词：${wordsList.join("、")}${wordsList.length}个词汇移动到`;
  moveParams = {
    categoryId: formState.hotWordCategoryId,
    ids: keys,
  };
  fetchHotwordMove();
};

//获取移动热词分组
const getHotWordsGroup = async () => {
  const data = await request.fetchHotWordCategorysList();
  data.forEach((element: any) => {
    element.value = element.cateName;
  });
  moveOptions.value = data;
};

const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除热词
  await request.fetchHotwordDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      hotDetailBaseTables.value.selectedRowKeys = [];
      getRecord();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

const getRecord = async (datas: dataSourceType = {}) => {
  // 获取热词分组表格数据
  const data: {} = {
    hotTerm: datas.hotTerm || "",
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    hotWordCategoryId: query.id || "",
  };
  console.log(data, 82913812);
  const telData = (await request.fetchHotwordPage(data)) || {};
  let reqData = telData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records.map((item: any, index: number) => {
    sourceData = {
      hotWord: item.hotWord,
      remark: item.remark,
      useCount: item.useCount,
      clickCount: item.clickCount,
      isTargetBlank: item.isTargetBlank,
      isEnable: item.isEnable,
      linkUrl: item.linkUrl || "",
      num: index + 1,
      cateName: item.cateName,
      hotWordCategoryId: item.hotWordCategoryId,
      id: item.id,
      oparation: ["移动", "编辑", "删除"],
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "").y;
    scroll.isFixed = getTableScroll(74, "").isFixed;
  });
};

const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  //切换分页器
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRecord(datas);
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
};

const switchChange = async (record: any) => {
  //是否启用开关
  const postData = { id: record.id };

  await request[record.isEnable ? "fetchHotwordEnable" : "fetchHotwordDisable"](postData)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecord(datas);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//computed
rowSelection = computed(() => {
  return hotDetailBaseTables.value.selectedRowKeys;
});
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm();
  console.log(btnPerm.value, 'btnPerm.value');
  getRecord();
  getHotWordsGroup();
});
</script>
<style lang="less" scoped>
.hotWord {
  width: 100%;
  height: calc(100% - 72px);
  padding: 24px;
  background-color: #fff;

  .hotWord_button {
    padding-bottom: 24px;
    display: flex;
    align-items: center;

    .hot-sec {
      color: #7f7f7f;

      span {
        color: #333;
      }
    }

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}



::v-deep(.ant-form-item) {
  display: flex;

  // margin-left: 28px;
  .ant-form-item-control {
    width: 512px;
    max-height: 80px;
    // margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 100px;
    text-align: right;
  }
}

::v-deep(.ant-form-item:nth-child(4)) {
  margin-bottom: 14px;
}

::v-deep(.ant-form-item:nth-child(5)) {
  margin-bottom: 14px;
}

.hotwordform {
  ::v-deep(.ant-form-item-label) {
    flex-grow: 0;
    width: auto;
    text-align: right;
  }
}

.editDetailHotWordForm {
  ::v-deep(.ant-form-item:first-child) {
    margin-top: -5px;
    margin-bottom: 19px;
  }
}

.ant-form-item:last-child {
  margin-top: -5px;
  margin-bottom: -5px;
}

.move-title {
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 24px;
}

.move-item {
  margin-bottom: 0 !important;
}

:deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 26px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.anticon-close-circle) {
  display: none;
}

.ant-row {
  flex-flow: row;
}

.model-tip {
  position: absolute;
  margin-top: 8px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
}

::v-deep(.ant-table-cell:nth-child(10)) {
  text-align: right;
}

::v-deep(.ant-table-cell-fix-left, .ant-table-cell-fix-right) {
  z-index: 999;
}</style>
